from twisted.protocols.ftp import FTPClientBasic, FTPClient, FTPFileListProtocol
from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor
 
class FTPClass:
 
    def __init__(self, username, password, hostname):
        self.data = {
            "username": username,
            "password": password,
            "hostname": hostname,
        }
 
        self.Connect()
 
    """ Events """
 
    def connectionMade(self, client):
        print "Connessione effettuata con successo"
        self.FTP = client
        self.FTP.pwd().addCallbacks(self.successResponse, self.failedResponse)
        self.getDirs()
 
    def connectionLost(self, reason):
        print "Connessione persa:"
        print "\t", reason
        self.FTP.quit()
        self.closeConnection()
 
    def connectionFailed(self, error):
        print "Connessione non riuscita:"
        print "\t", error
        self.closeConnection()
 
    def successResponse(self, message):
        print "Operazione effettuata:"
        print "\t", message
 
    def failedResponse(self, message):
        print "Operazione non riuscita:"
        print "\t", message
 
    """ Some useful methods """
 
    def Connect(self):
        Client = ClientCreator(reactor, FTPClient, self.data["username"], self.data["password"], 0)
        Connection = Client.connectTCP(self.data["hostname"], 21)
        Connection.addCallbacks(self.connectionMade, self.connectionFailed)
        reactor.run()
 
    def getDirs(self, *args):
 
        def Parse(list, protocol):
            print "Lettura lista remota:"
            for file in protocol.files:
                 print "\t", "%s %s %s" % (file['filename'].ljust(20), str(file['size']).ljust(10), file['date'].replace("  "," ").ljust(20))
            print "Totale: %d oggetti" % (len(protocol.files))
            self.currentDirs = protocol.files
 
        ListProtocol = FTPFileListProtocol()
        List = self.FTP.list(".", ListProtocol)
        List.addCallbacks(Parse, self.failedResponse, callbackArgs=(ListProtocol,))
 
 
    def closeConnection(self):
        reactor.stop()